const Api = require("./Api");

class commonHeadersAnalyzer {

    /**
     *
     * @param {Api[]} apis
     * @param {{headerNames: string[], customHeaders: Object}} headerConfig
     */
    constructor(apis, headerConfig) {
        this.apis = apis;
        this.headerConfig = headerConfig;
        /** @type {{name: string, value: string}[]} */
        this.commonHeaders = [];
    }

    /**
     * 
     * @returns {{name: string, value: string}[]}
     */
    analyze() {
        if (this.headerConfig && this.headerConfig.headerNames) {
            this.headerConfig.headerNames.forEach(headerName => {
                for (const api of this.apis) {
                    const header = api.headers.find(header => header.name.toLowerCase() === headerName.toLowerCase());
                    if (header) {
                        this.commonHeaders.push({ name: header.name, value: header.value });
                        break;
                    }
                }
            });
        }
        if (this.headerConfig && this.headerConfig.customHeaders) {
            for (const headerName in this.headerConfig.customHeaders) {
                const headerValue = this.headerConfig.customHeaders[headerName];
                this.commonHeaders.push({ name: headerName, value: headerValue });
            }
        }
        return this.commonHeaders;
    }
}

module.exports = commonHeadersAnalyzer;